package be.kuleuven.mume.rest;

import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import org.ariadne_eu.hcifetcher.rest.RestUtils;

import be.kuleuven.mume.PMF;
import be.kuleuven.mume.beans.ProfBean;
import be.kuleuven.mume.beans.VakBean;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;

@Path("/test")
public class Test {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5978140401583941374L;
	private static final Logger log = Logger.getLogger(Test.class.getName());

	@Path("/")
	@GET
	@Produces("application/json")
	public String doGet(){
		deleteSince();
		return "Succes";
	}
	
	private void generateDb(){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		ProfBean prof = new ProfBean();
		prof.setMail("DE@gmail.com");
		prof.setName("Duval Eric");
		prof.setTwitterName("duvaleric");
		
		pm.makePersistent(prof);
		
		VakBean vak = new VakBean();
		vak.setHashTag("mume11");
		vak.setName("Multimedia");
		vak.setProf(prof.getId());
		
		pm.makePersistent(vak);
	}

	private String deleteSince() {
		try {
			Query q = new Query("Entry");
			//q.addFilter("datestamp", FilterOperator.GREATER_THAN, "DATE('2011-11-23')");
			DateFormat df = new SimpleDateFormat ("yyyy-mm-dd");
			Date since = df.parse("2011-12-09");
			q.addFilter("datestamp", FilterOperator.GREATER_THAN, since);
			DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
			PreparedQuery qp = datastore.prepare(q);
			for (Entity entry : qp.asIterable()) {
				datastore.delete(entry.getKey());
			}
			
			q = new Query("Tweet");
			//q.addFilter("datestamp", FilterOperator.GREATER_THAN, "DATE('2011-11-23')");
			q.addFilter("datestamp", FilterOperator.GREATER_THAN, since);
			datastore = DatastoreServiceFactory.getDatastoreService();
			qp = datastore.prepare(q);
			for (Entity entry : qp.asIterable()) {
				datastore.delete(entry.getKey());
			}
			return "succes";
			} catch (Exception e) {
				log.log(Level.SEVERE, "Exception", e);
			}
			return "Failed";
			/*} catch (UserNotLoggedInException e) {
				return e.toJsonString();
			}*/
	}
}
